package controller.view;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import command.Command;

import model.Project;
import model.Statechart;
import model.StatechartComponentManager;
import model.Workspace;

import controller.ApplicationController;

import view.interfaces.screen.project.ProjectView;
import view.interfaces.workspace.WorkspaceView;

public class ProjectController {

	private final ApplicationController applicationController;
	private final ProjectView projectView;
	private final Set<WorkspaceController> workspaceControllers;
	private StatechartComponentManager statechartComponentManager;
	private Project project;

	public ProjectController(final ApplicationController applicationController,
			final ProjectView projectView) {
		super();
		this.applicationController = applicationController;
		this.projectView = projectView;
		this.workspaceControllers = new HashSet<WorkspaceController>();
	}

	public void executeCommand(Command command) {
		applicationController.runLocalCommandAndDispatch(command);
	}

	public void setProject(Project project) {
		if (this.project != null) {

		}
		this.project = project;
		this.statechartComponentManager = new StatechartComponentManager(
				this.project);
	}

	public StatechartComponentManager getStatechartComponentManager() {
		return statechartComponentManager;
	}

	public Set<Statechart> getStatecharts() {
		return project == null ? null : project.getStatecharts();
	}

	public boolean isLocked(Statechart statechart, String userName) {
		WorkspaceController workspaceController = getWorkspaceControllerForUser(userName);
		if (workspaceController != null) {
			return workspaceController.getLockedStatechartIds().contains(
					statechart.getId());
		}
		return false;
	}

	private WorkspaceController getWorkspaceControllerForUser(String userName) {
		Iterator<WorkspaceController> iter = workspaceControllers.iterator();
		while (iter.hasNext()) {
			WorkspaceController workspaceController = (WorkspaceController) iter
					.next();
			if (workspaceController.getWorkspace().getUser().getName()
					.equalsIgnoreCase(userName)) {
				return workspaceController;
			}
		}
		return null;
	}

	public WorkspaceController createWorkspaceController(Workspace workspace,
			WorkspaceView workspaceView) {
		WorkspaceController workspaceController = new WorkspaceController(
				workspace, this, workspaceView);
		workspaceControllers.add(workspaceController);
		return workspaceController;
	}

	public boolean isStatechartNameAvailable(String input) {
		for (Statechart statechart : project.getStatecharts()) {
			if (statechart.getName().equalsIgnoreCase(input)) {
				return false;
			}
		}
		return true;
	}

}
